package com.startx.http.system.encrypt.base64;

import java.io.IOException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class SafeUrlBase64 {
	
	public static String safeUrlBase64Encode(byte[] data) {
		try {
			String encodeBase64 = new BASE64Encoder().encode(data);
			String safeBase64Str = encodeBase64.replace('+', '-');
			safeBase64Str = safeBase64Str.replace('/', '_');
			safeBase64Str = safeBase64Str.replaceAll("=", "");
			return safeBase64Str;
		} catch (Exception e) {
			return "";
		}
	}

	public static byte[] safeUrlBase64Decode(final String safeBase64Str) {
		try {
			String base64Str = safeBase64Str.replace('-', '+');
			base64Str = base64Str.replace('_', '/');
			int mod4 = base64Str.length() % 4;
			if (mod4 > 0) {
				base64Str = base64Str + "====".substring(mod4);
			}
			return new BASE64Decoder().decodeBuffer(base64Str);
		} catch (IOException e) {
			return new byte[]{};
		}
		
	}
}
